package com.weishaoying.thrift.learn.service.asyn;

import com.meituan.service.mobile.mtthrift.callback.OctoThriftCallback;
import com.weishaoying.thrift.learn.entity.User;
import com.weishaoying.thrift.learn.service.Client;
import com.weishaoying.thrift.learn.service.UserService;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * IDL方式异步 - 1.Future
 *
 * @author WeiShaoying
 * @date 2018/9/12
 */
public class FutureMain {

    private static final Logger logger = LoggerFactory.getLogger(Client.class);

    public static void main(String[] args) throws InterruptedException {
        BeanFactory beanFactory = new ClassPathXmlApplicationContext("client.xml");
        UserService.AsyncIface client = (UserService.AsyncIface) beanFactory.getBean("clientProxy"); //注意是AsyncIface，不是Iface
        Thread.sleep(5000);

        OctoThriftCallback<UserService.AsyncClient.getUserById_call, User> getUserByIdCallback = new OctoThriftCallback();
        OctoThriftCallback<UserService.AsyncClient.getAllUsers_call, List<User>> getAllUsersCallback = new OctoThriftCallback();

        //每次调用使用不同的OctoThriftCallback实例，切记不要复用
        try {
            System.out.println("----------调用 client.getUserById()----------");
            client.getUserById(123, getUserByIdCallback);
            client.getAllUsers(getAllUsersCallback);
            System.out.println("----------client.getAllUsers() 结束>> ----------\n");
        } catch (TException e) {
            e.printStackTrace();
        }
        System.out.println("----------开始：getUserByIdCallback.getFuture()");
        Future userFuture = getUserByIdCallback.getFuture();

        Future getAllUsersCallbackFuture = getAllUsersCallback.getFuture();
        System.out.println("----------getAllUsersCallback.getFuture()结束\n");

        //TODO: future.get()可以设置方法级别超时
        try {
            User user = (User) userFuture.get();
            System.out.println("----" + user);
            System.out.println();
            List<User> userList = (List<User>) getAllUsersCallbackFuture.get();
            userList.forEach(System.out::println);

        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
